﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace CDDocumentExtractor
{
    public partial class frmTOCExtractor : Form
    {
        Db4objects.Db4o.IObjectContainer db = DataAccess.GetDataContainer();
        int itemCount = 0;

        List<FolderEntity> FoldersInQueue;
        string rows = "<tr\\b[^>]*>(.*?)</tr>";
        string cols = "<td\\b[^>]*>(.*?)</td>";
        System.Text.RegularExpressions.Regex rxRows;
        System.Text.RegularExpressions.Regex rxCols;
        List<DocumentsToDownload> documents = new List<DocumentsToDownload>();

        public frmTOCExtractor()
        {
            InitializeComponent();
        }

        public void ExtractDocumentList()
        {
            documents.Clear();
            lblDocuments.Text = "Working...";

            Random r = new Random(0);
            Color bgColor;

            foreach (var folder in FoldersInQueue)
            {
                if (folder.FolderPath.Trim().Length > 0)
                {
                    try
                    {
                        this.Text = "Currently Processing : " + folder;

                        bgColor = System.Drawing.Color.FromArgb(r.Next(255), r.Next(255), r.Next(255));
                        Application.DoEvents();
                        WebUtility wu = new WebUtility();
                        string docs = wu.RequestDocument(folder.FolderPath.Trim() + "index.html?f=templates$fn=document-frame.htm");

                        File.WriteAllText(WebUtility.Read("errorFile"), docs);

                        var matchingRows = rxRows.Matches(docs);

                        for (int i = 0; i < matchingRows.Count; i++)
                        {
                            var docRow = matchingRows[i];

                            var matchingCols = rxCols.Matches(docRow.Value);
                            var linkAddress = matchingCols[0].Value;
                            var start = linkAddress.IndexOf("<a href=");
                            if (start >= 0)
                                start += 9;

                            var end = linkAddress.IndexOf("> <p");
                            if (end >= 0)
                                end -= 1;
                            linkAddress = linkAddress.Substring(start, end - start);

                            string Title = "", DecidedOn = "", Subject = "";


                            if (matchingCols.Count > 0)
                                Title = System.Text.RegularExpressions.Regex.Replace(matchingCols[0].Value, "<.*?>", string.Empty).Trim();

                            if (matchingCols.Count > 1)
                                DecidedOn = System.Text.RegularExpressions.Regex.Replace(matchingCols[1].Value, "<.*?>", string.Empty).Trim();

                            if (matchingCols.Count > 2)
                                Subject = System.Text.RegularExpressions.Regex.Replace(matchingCols[2].Value, "<.*?>", string.Empty).Trim();
                            Application.DoEvents();

                            var doc = new DocumentsToDownload()
                            {
                                DocumentDownloadPath = folder.FolderPath.Trim() + linkAddress,
                                DocumentPath = linkAddress,
                                DocumentTitle = Title,
                                DecidedOn = DecidedOn,
                                Subject = Subject
                            };
                            documents.Add(doc);
                            StoreDocumentInDB(doc);

                            //Add item to list view as well
                            var item = lvDocuments.Items.Add(Subject);
                            item.BackColor = bgColor;
                            item.SubItems.Add(DecidedOn);
                            item.SubItems.Add(Title);
                            item.SubItems.Add(linkAddress);
                            item.EnsureVisible();
                        }

                        Application.DoEvents();

                        folder.Processed = true;
                        db.Store(folder);
                        db.Commit();
                    }
                    catch
                    {
                    }
                }
            }

            #region Commented XML generation Code
            /*            if (File.Exists(Path.Combine(Application.StartupPath, "DocumentList.xml")))
            {
                File.Move(Path.Combine(Application.StartupPath, "DocumentList.xml"), Path.Combine(Application.StartupPath, DateTime.Now.ToString().Replace(' ', '_').Replace(':', '_').Replace('/', '_') + "_DocumentList.xml"));
            }

            System.Xml.XmlTextWriter xml = new System.Xml.XmlTextWriter(Path.Combine(Application.StartupPath, "DocumentList.xml"), null);
            xml.WriteStartDocument();

            xml.Indentation = 3;
            xml.IndentChar = ' ';

            xml.WriteStartElement("Documents");
            xml.WriteString(Environment.NewLine);
            foreach (var item in documents)
            {
                xml.WriteStartElement("Document");
                xml.WriteStartAttribute("Title");
                xml.WriteString(item.DocumentTitle);
                xml.WriteEndAttribute();

                xml.WriteStartAttribute("Subject");
                xml.WriteString(item.Subject);
                xml.WriteEndAttribute();

                xml.WriteStartAttribute("DecidedOn");
                xml.WriteString(item.DecidedOn);
                xml.WriteEndAttribute();

                xml.WriteStartAttribute("FullDownloadPath");
                xml.WriteString(item.DocumentDownloadPath);
                xml.WriteEndAttribute();

                xml.WriteStartAttribute("DocumentPath");
                xml.WriteString(item.DocumentPath);
                xml.WriteEndAttribute();

                xml.WriteStartAttribute("Processed");
                xml.WriteString("0");
                xml.WriteEndAttribute();

                xml.WriteStartAttribute("ManuID");
                xml.WriteString("");
                xml.WriteEndAttribute();

                xml.WriteStartAttribute("FileName");
                xml.WriteString("");
                xml.WriteEndAttribute();

                xml.WriteEndElement();
                xml.WriteString(Environment.NewLine);
            }
            xml.WriteEndElement();

            xml.WriteEndDocument();
            xml.Close();*/
            #endregion

            lblDocuments.Text = "Documents Found for Extraction";
            MessageBox.Show(documents.Count + " no of Documents found");
        }

        public void StoreDocumentInDB(DocumentsToDownload doc)
        {
            //var document = db.Query<DocumentsToDownload>(d => d.DocumentPath.Equals(doc.DocumentPath)).FirstOrDefault();
            //if (document == null)
            //{
            db.Store(doc);

            if (itemCount == 1000)
                db.Commit();
            //}
        }

        private void frmTOCExtractor_Load(object sender, EventArgs e)
        {
            this.FormClosing += new FormClosingEventHandler(frmTOCExtractor_FormClosing);

            rxRows = new System.Text.RegularExpressions.Regex(rows, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            rxCols = new System.Text.RegularExpressions.Regex(cols, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            FoldersInQueue = db.Query<FolderEntity>(fl => !fl.Processed).OrderBy(fe => fe.FolderID).ToList();

            foreach (var item in FoldersInQueue)
            {
                lvFolders.Items.Add(item.FolderPath);
            }
        }

        void frmTOCExtractor_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                this.db.Close();
            }
            catch
            {
            }
        }

        private void cmdDoclist_Click(object sender, EventArgs e)
        {
            ExtractDocumentList();
        }
    }
}
